package com.gl.order.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.entity.AreaDict;
import com.gl.order.mapper.AreaDictMapper;
import com.gl.order.service.AreaService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: liangSY
 * @Date: 2021/6/24 14:26
 * @ClassName: AreaServiceImpl
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaDictMapper, AreaDict> implements AreaService {

    @Override
    public List<Tree<Integer>> getAreaToThree() {
        List<AreaDict> areas = list();
        List<Tree<Integer>> list = CoverToTree(areas);
        return list;
    }

    @Override
    public List<Tree<Integer>> getAreaByPid(String pid) {
        LambdaQueryWrapper<AreaDict> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AreaDict::getParentId, pid);
        List<AreaDict> areas = list(queryWrapper);
        List<Tree<Integer>> list = CoverToTree(areas);
        return list;
    }

    @Override
    public List<Tree<Integer>> getAreaByLv(Integer lv) {
        LambdaQueryWrapper<AreaDict> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AreaDict::getLv, lv);
        List<AreaDict> areas = list(queryWrapper);
        List<Tree<Integer>> list = CoverToTree(areas);
        return list;
    }


    /**
     *
     * 将地区列表统一转为tree的格式返回
     */
    private List<Tree<Integer>> CoverToTree(List<AreaDict> areas) {
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("sort");
        // 转换器
        List<Tree<Integer>> list = TreeUtil.build(areas, 0, treeNodeConfig, (area, tree) -> {
            tree.setId(area.getId());
            tree.setParentId(area.getParentId());
            tree.setWeight(area.getSort());
            tree.setName(area.getName());
        });
        return list;
    }


}
